package com.llkj.contractmanagement.utils;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;


import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.http.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadService extends Service {

    public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory() + "/downloads/";
    private String path;// 下载链接
    private String fileName = "htgl.apk";// 文件名
    private NotificationManager notificationManager;
    private NotificationCompat.Builder builder;
    private int progress;
    private static final int DOWN = 0;
    private static final int URL_ERROR = 1;
    private static final int NET_ERROR = 2;
    private static final int DOWNLOAD_SUCCESS = 3;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case DOWN:
                    builder.setProgress(100, progress, false).setContentText(progress + "%");
                    notificationManager.notify(100, builder.build());
                    break;
                case DOWNLOAD_SUCCESS:
                    notificationManager.cancel(100);
                    // 下载完成
                    installApk(DownloadService.this, new File(DOWNLOAD_PATH, fileName));
                    //关闭服务
                    DownloadService.this.stopSelf();
                    break;
                case URL_ERROR:
                    ToastUtil.makeShortText(DownloadService.this, "下载地址错误");
                    break;
                case NET_ERROR:
                    ToastUtil.makeShortText(DownloadService.this, "请检查网络!");
                    break;
            }
        }

    };

    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            path = intent.getStringExtra("url");
            if (!StringUtil.isEmpty(path)) {
                if (path.endsWith(".apk")) {
                    createNotification();
                    new DownloadThread().start();
                } else {
                    mHandler.sendEmptyMessage(URL_ERROR);
                }
            } else {
                mHandler.sendEmptyMessage(URL_ERROR);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 下载线程
     *
     * @author dong
     */
    class DownloadThread extends Thread {
        @Override
        public void run() {
            HttpURLConnection conn = null;
            InputStream input = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL(path);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Charser", "GBK,utf-8;q=0.7,*;q=0.3");
                File dir = new File(DOWNLOAD_PATH);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                // 设置文件写入位置
                File file = new File(dir.getAbsolutePath(), fileName);
                long mFinished = 0;
                // 开始下载
                if (conn.getResponseCode() == 200) {
                    // 读取数据
                    fos = new FileOutputStream(file);
                    int length = conn.getContentLength();
                    input = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    long time = System.currentTimeMillis();
                    while ((len = input.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        // 写入文件
                        mFinished += len;
                        if (System.currentTimeMillis() - time > 1000) {
                            time = System.currentTimeMillis();
                            progress = (int) (((float) mFinished / length) * 100);
                            mHandler.sendEmptyMessage(DOWN);
                        }
                    }
                    mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);
                } else {
                    mHandler.sendEmptyMessage(NET_ERROR);
                    Log.e("dyj", conn.getResponseCode() + "");
                }
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(NET_ERROR);
            } finally {
                try {
                    if (conn != null) {
                        conn.disconnect();
                    }
                    if (input != null) {
                        input.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void createNotification() {
        builder = new NotificationCompat.Builder(this);
        builder.setContentTitle("正在下载：HRCM");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setOngoing(true);
        builder.setProgress(100, progress, false)
                .setContentText(progress + "%");
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(100, builder.build());
    }

    /**
     * 安装apk
     *
     * @param context 上下文
     * @param file    APK文件
     */
    public static void installApk(Context context, File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
